/**
 * 
 */
package cr.co.tse.padronelectoral.csv;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

/**
 * This dao reads the fields of the files, like .dat.
 * @author jsanca
 *
 */
public class FieldRowReaderGenericDAOImpl implements RowReaderGenericDAO {

	private Integer [] columnSizes = null;
	private int totalSize = 0;
	private LineNumberReader reader = null;
	
	public FieldRowReaderGenericDAOImpl(Integer [] columnSizes, File file) throws FileNotFoundException {

		this.columnSizes = columnSizes;
		for (int size : columnSizes) {
			
			this.totalSize += size;
		}
		
		this.reader = new LineNumberReader (new FileReader(file));
	} // FieldRowReaderGenericDAOImpl.

	/* (non-Javadoc)
	 * @see cr.co.tse.padronelectroral.csv.RowReaderGenericDAO#next()
	 */
	@Override
	public String[] next() throws IOException {
		
		String line = this.reader.readLine();
		List<String> columns = null;
		int offset = 0;
		int endIndex = 0;
		
		if (null != line) {
			
			columns = new ArrayList<String> ();
			
			if (line.length() >= this.totalSize) {
			
				for (int size : this.columnSizes) {
					
					endIndex = (-1 == size)?line.length()-1:offset+size;
					
					columns.add(this.parseColumn(line, offset, endIndex));
					offset += size;
				}
			}
		}
		
		return (null != columns)?
				(String[]) columns.toArray(new String[]{}):null;
	} // next.
	
	private String parseColumn (String line, int offset, int size) {
		
		return line.substring(offset, size);
	} // parseColumn.

	/* (non-Javadoc)
	 * @see java.io.Closeable#close()
	 */
	@Override
	public void close() throws IOException {

		if (null != reader) {
			
			reader.close();
		}
	}

}
